﻿using DevSupport.Extensions;
using System.Net;

namespace DevSupport.Middleware
{
    public class LoginMiddleware
    {

        private readonly RequestDelegate next;

        public LoginMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var url = context.GetRequestUrl();
            if (!context.IsAuthorized() && !url.Contains("login"))
            {
                context.Response.Redirect("/pages/login.html");
                return; 
            }
            await next.Invoke(context);
        } 
        /// <summary>
        /// 判断是不是本地访问
        /// 本地不用swagger拦截
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool IsLocalRequest(HttpContext context)
        {
            if (context.Connection.RemoteIpAddress == null && context.Connection.LocalIpAddress == null)
            {
                return true;
            }
            if (context.Connection.RemoteIpAddress!.Equals(context.Connection.LocalIpAddress))
            {
                return true;
            }
            if (IPAddress.IsLoopback(context.Connection.RemoteIpAddress))
            {
                return true;
            }
            return false;
        }
    }
    // 定义扩展
    public static class LoginAuthorizeExtensions
    {
        public static IApplicationBuilder UseLoginAuthorized(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LoginMiddleware>();
        }
    }
}
